-- Leviathan (c) v.v.balashoff
local Class = require('leviathan/Class')

local SliderSystem = Class:derive('UISliderSystem')

function SliderSystem:new(domain)
    self.name = 'SliderSystem'
    self.domain = domain
end

function SliderSystem:update(dt)
    local r = self.domain.components['Slider']
    for _, c in pairs(r) do
        if c.id == 'SliderComponent' then
            c.velocity = c.velocity - math.floor(c.velocity * math.min(dt * 10, 1))
            local valuePrev = c.value
            c.value = c.value - c.velocity * dt * 0.0005
            if c.value < 0 then
                c.value = 0
            end
            if c.value > 1 then
                c.value = 1
            end
            if not (valuePrev == c.value) then
                c.entity.domain.changed = true
            end
        end
    end
end

-- TODO qqq
function SliderSystem:clickEntity(domain, entity)
    local mx, my = love.mouse.getPosition()
    -- get coordinates
    local sx, sy, sw, sh
    sx = entity.x
    sy = entity.y
    local slider = entity:getComponent('Slider')
    sw = slider.w
    sh = slider.h
    local parentX, parentY = entity:getParentRealCoordinates()
    sx = parentX + sx
    sy = parentY + sy
    -- get slider direction
    local vertical = false
    if sw == 0 then
        vertical = true
    end
    -- calculate new value
    local vol
    if vertical then
        vol = (my - sy) / sh
    else
        vol = (mx - sx) / sw
    end
    if not (slider.volume == vol) then
        -- volume changed
        slider.view.changed = true
        local parent = slider.entity
        local content = slider.content
        if vertical then
            local viewH = slider.view.sizeY
            local diff = parent.maxY - viewH
            slider.target.y = math.floor(-diff * vol)
        else
            -- TODO qqq!
            print('TODO horizontal!')
        end
    end
    slider.volume = vol
end

return SliderSystem
